package com.ynu.springbootappdemo.service;

import cn.hutool.core.bean.BeanUtil;
import com.ynu.springbootappdemo.dao.IDeliveryAddressDao;
import com.ynu.springbootappdemo.dao.IUserDao;
import com.ynu.springbootappdemo.model.dto.address.UpdateAddressDTO;
import com.ynu.springbootappdemo.model.entity.Customer;
import com.ynu.springbootappdemo.model.entity.DeliveryAddress;
import com.ynu.springbootappdemo.model.entity.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class DeliveryAddressService {

    @Resource
    private IDeliveryAddressDao dao;


    @Resource
    private IUserDao userDao;
    @Resource
    private UserService userService;

    public  List<DeliveryAddress> findAll(HttpServletRequest request){
        return dao.findAllByCustomer(userService.getLoginUser(request));
    }

    public DeliveryAddress findById(Long id,HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        return dao.findDeliveryAddressByCustomerAndId(loginUser,id);
    }

    public DeliveryAddress deleteById(Long id,HttpServletRequest request){
        DeliveryAddress address = this.findById(id, request);
        address.setIsDeleted(1);
        return dao.save(address);
    }

    public  DeliveryAddress saveAddress(UpdateAddressDTO dto, HttpServletRequest request){
        Customer loginUser = (Customer)userService.getLoginUser(request);
        List<DeliveryAddress> addressesList = loginUser.getDeliveryAddresses();
        //取消其他地址的默认状态
        if (dto.isDefaultAddress()){
            for (DeliveryAddress addresses : addressesList) {
                if (addresses.isDefaultAddress()) {
                    addresses.setDefaultAddress(false);
                }
            }
        }
        DeliveryAddress deliveryAddress = null;
        if (dto.getId() > 0){
            //更新
            deliveryAddress = this.findById(dto.getId(), request);
            BeanUtil.copyProperties(dto,deliveryAddress);
            return dao.save(deliveryAddress);
        }else {
            //新建
            deliveryAddress = new DeliveryAddress();
            BeanUtil.copyProperties(dto,deliveryAddress);
            addressesList.add(deliveryAddress);
            loginUser.setDeliveryAddresses(addressesList);

            Customer save = userDao.save(loginUser);
            List<DeliveryAddress> list = save.getDeliveryAddresses();

            return dao.findDeliveryAddressByCustomerAndId(save,list.get(list.size()-1).getId());
        }

    }

}
